<?php

namespace app\admin\service;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

use app\admin\model\Product as ProductMdl;
use app\admin\model\Productcategory;
use app\admin\model\Supplier;
use app\admin\model\Brand;

use think\Db;
use think\Exception;

class Product
{

    /**
     * 生成商品二维码
     */
    public static function createQrCode($data){
        // Create a basic QR code
        //$qrCode = new QrCode('Product');
        $qrCode = new QrCode();
        //$qrCode->setText('https://shop1.178md.com/admin/product/index.html');
        $text = json_encode([
            'appId' => config('wx.app_id'),
            'productId' => $data['id']
        ]);
        $qrCode->setText($text);
        $qrCode->setSize(300);

        //$uploadPath = ROOT_PATH . 'public' . DS . 'upload' . DS;
        $uploadPath = config('path.Upload_path');
        $filePath = 'qrcode' . DS . 'product' . DS . date('Y-m-d');
        $fileName = $filePath . '/product_' . mt_rand(1000, 9999) . date('ymdHis');
        // 检查文件或目录是否存在
        if(!file_exists($uploadPath . $filePath)){
            mkdir($uploadPath .$filePath, 0777, true);
        }

        // 设置高级选项
        $qrCode->setWriterByName('png');
        $qrCode->setMargin(10);
        $qrCode->setEncoding('UTF-8');
        $qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        $qrCode->setLabel('', 16, ROOT_PATH . 'vendor/endroid/qr-code/assets/fonts/noto_sans.otf', LabelAlignment::CENTER);
        $logo = $data['img_url'];
        // 缩放logo
        $thumb = $uploadPath . $filePath . '/thumb_' . mt_rand(1000, 9999) . '.jpg';
        $logo = self::thumbImage($logo, 50, 50, $thumb);
        $qrCode->setLogoPath($logo);
        //$qrCode->setLogoPath(ROOT_PATH . 'vendor/endroid/qr-code/assets/images/symfony.png');
        $qrCode->setLogoSize(50, 50);
        $qrCode->setRoundBlockSize(true);
        $qrCode->setValidateResult(false);
        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);

        // 直接输出二维码
        //header('Content-Type: '.$qrCode->getContentType());
        //echo $qrCode->writeString();

        // 保存到文件
        $qrCode->writeFile($uploadPath . $fileName . '.png');

        @unlink($thumb);

        // Create a response object
        //$response = new QrCodeResponse($qrCode);
        return $fileName . '.png';
    }

    /*public static function createQrCode($data){
        import('phpqrcode.phpqrcode', EXTEND_PATH);

        $content = $data['id']; // 二维码内容
        $errorCorrectionLevel = 'H'; // 容错级别
        $matrixPointSize = 10; // 生成图片大小

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'qrcode' . DS . 'product' . DS . date('Y-m-d');
        $fileName = $filePath . '/product_' . date('y-m-d-H-i-s') . '.png';
        // 检查文件或目录是否存在
        if(!file_exists($filePath)){
            mkdir($filePath, 0777, true);
        }

        $QRcode = new \QRcode();
        $QRcode::png($content, $fileName, $errorCorrectionLevel, $matrixPointSize, 2);
        $logo = $data['img_url'];
        // 缩放logo
        //$thumb = $filePath . '/thumb_' . mt_rand(1000, 9999);
        //$logo = self::resizeImage(imagecreatefromstring(file_get_contents($logo)), 50, 50, $thumb, '.png');
        $thumb = $filePath . '/thumb_' . mt_rand(1000, 9999) . '.jpg';
        $logo = self::thumbImage($logo, 50, 50, $thumb);

        $QR = $fileName; // 已经生成的原始二维码图
        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            // 重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
        }

        imagepng($QR, $fileName);
        imagedestroy($QR);

        //@unlink($thumb);

        return $fileName;
    }*/

    /**
     * 等比例缩放图片
     *
     * 新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)
     * @param string $im
     * @param int $maxwidth 生成图像宽
     * @param int $maxheight 生成图像高
     * @param string $filename 生成图像名称
     * @param string $filetype 文件类型 (.jpg/.gif/.png)
     * @return string
     */
    public static function resizeImage($im, $maxwidth, $maxheight, $filename, $filetype)
    {
        $pic_width = imagesx($im);
        $pic_height = imagesy($im);

        if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
            if ($maxwidth && $pic_width > $maxwidth) {
                $widthratio = $maxwidth / $pic_width;
                $resizewidth_tag = true;
            }
            if ($maxheight && $pic_height > $maxheight) {
                $heightratio = $maxheight / $pic_height;
                $resizeheight_tag = true;
            }
            if ($resizewidth_tag && $resizeheight_tag) {
                if ($widthratio < $heightratio){
                    $ratio = $widthratio;
                } else {
                    $ratio = $heightratio;
                }
            }
            if ($resizewidth_tag && !$resizeheight_tag){
                $ratio = $widthratio;
            }
            if ($resizeheight_tag && !$resizewidth_tag){
                $ratio = $heightratio;
            }

            $newwidth = $pic_width * $ratio;
            $newheight = $pic_height * $ratio;

            if (function_exists("imagecopyresampled")) {
                $newim = imagecreatetruecolor($newwidth, $newheight);
                imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
            } else {
                $newim = imagecreate($newwidth, $newheight);
                imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
            }

            $filename = $filename . $filetype;
            //imagejpeg($newim, $filename);
            imagepng($newim, $filename);
            imagedestroy($newim);
        } else {
            $filename = $filename . $filetype;
            //imagejpeg($im, $filename);
            imagepng($im, $filename);
        }

        return $filename;
    }

    /**
     * 得到缩略图
     *
     * @param string $image 原图路径
     * @param int $thumb_x 缩略图宽度
     * @param int $thumb_y 缩略图高度
     * @param string $filename 缩放图路径
     * @return string
     */
    public static function thumbImage($image, $thumb_x, $thumb_y, $filename)
    {
        $imgstream = file_get_contents($image);
        $im = imagecreatefromstring($imgstream);
        $x = imagesx($im);//获取图片的宽
        $y = imagesy($im);//获取图片的高

        // 缩略后的大小
        $xx = $thumb_x;
        $yy = $thumb_y;

        if ($x > $y) {
            //图片宽大于高
            $sx = abs(($y - $x) / 2); //abs() 函数返回一个数的绝对值
            $sy = 0;
            $thumbw = $y;
            $thumbh = $y;
        } else {
            //图片高大于等于宽
            $sy = abs(($x - $y) / 2.5);
            $sx = 0;
            $thumbw = $x;
            $thumbh = $x;
        }
        if (function_exists("imagecreatetruecolor")) {
            $dim = imagecreatetruecolor($xx, $yy); // 创建目标图gd2
        } else {
            $dim = imagecreate($xx, $yy); // 创建目标图gd1
        }
        imageCopyreSampled($dim, $im, 0, 0, $sx, $sy, $xx, $yy, $thumbw, $thumbh);

        imagejpeg($dim, $filename);
        imagedestroy($dim);

        return $filename;
    }

    /**
     * 导出数据
     */
    public static function export($request){
        $param = $request->param();

        $where = [
            'status' => 1,
        ];

        $model = new ProductMdl();
        $data = $model->where($where)->order('create_date', 'asc')->select();
        if(count($data) <= 0){
            return [
                'code' => 2,
                'msg' => '没有数据！'
            ];
        }

        foreach ($data as $key => $val) {
            // 分类
            $val['category_id'] = Productcategory::where('id', $val['category_id'])->value('name');
            // 单位
            $val['unit'] = show_product_unit($val['unit']);
            // 进货价
            $val['purchase_price'] = $val['purchase_price'] / 100;
            // 售价
            $val['price'] = $val['price'] / 100;
            // 批发价
            $val['wholesale_price'] = $val['wholesale_price'] / 100;
            // 最低售价
            $val['lowest_price'] = $val['lowest_price'] / 100;
            // 供货商
            $val['supplier_id'] = Supplier::where('id', $val['supplier_id'])->value('name');
            // 品牌
            $val['brand_id'] = Brand::where('id', $val['brand_id'])->value('name');
            // 保质期
            $val['quality_time'] = $val['quality_time'] . ' 天';
            // 计价方式
            switch ($val['price_type']) {
                case 1: $val['price_type'] = '普通'; break;
                case 2: $val['price_type'] = '称重'; break;
                case 3: $val['price_type'] = '计数'; break;
                default : break;
            }
            // 是否支持退款
            switch ($val['after_sale_type']) {
                case 1: $val['after_sale_type'] = '支持'; break;
                case 2: $val['after_sale_type'] = '不支持'; break;
                default : $val['after_sale_type'] = '不支持'; break;
            }
            // 是否支持退款退货
            switch ($val['is_returned']) {
                case 1: $val['is_returned'] = '支持'; break;
                case 2: $val['is_returned'] = '不支持'; break;
                default : $val['is_returned'] = '不支持'; break;
            }
        }

        $cellName = array(
            'A' => ['id', '序号'],
            'B' => ['img_url', '封面图'],
            'C' => ['name', '商品名称'],
            'D' => ['spec', '规格'],
            'E' => ['bar_code', '条码'],
            'F' => ['category_id', '分类'],
            'G' => ['unit', '单位'],
            'H' => ['purchase_price', '进货价'],
            'I' => ['price', '售价'],
            'J' => ['wholesale_price', '批发价'],
            'K' => ['lowest_price', '最低售价'],
            'L' => ['supplier_id', '供货商'],
            'M' => ['brand_id', '品牌'],
            'N' => ['packing', '包装'],
            'O' => ['address', '产地'],
            'P' => ['quality_time', '保质期'],
            'Q' => ['storage_mode', '贮存方式'],
            'R' => ['price_type', '计价方式'],
            'S' => ['fresh_code', '生鲜码'],
            'T' => ['plu_code', 'PLU码'],
            'U' => ['after_sale_type', '是否支持退款'],
            'V' => ['is_returned', '是否支持退款退货'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'product' . DS . date('Y-m-d');
        $fileName = $filePath . '/product_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel::exportExcel('商品', $data, $cellName, $filePath, $fileName);

        return [
            'code' => 1,
            'msg' => '导出成功！'
        ];
    }

}